﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data.Common;

namespace Toyger.Common.Connections
{
    /// <summary>
    /// 
    /// </summary>
    public class ConnectionObject
    {
        #region event
        #endregion

        public Guid ID { get; private set; }
        public String Name { get;  set; }
        public String ConnectionString { get; private set; }
        public String ServerType { get; private set; }
        public DateTime CteateDate { get; private set; }
        Dictionary<String, String> customerProperties = new Dictionary<string, string>();
        public Dictionary<String, String> CustomerProperties { get { return customerProperties; } }

        public static ConnectionObject FillConnectionObject(Guid id, String name, String connectionString, String servertype, DateTime createDate)
        {
            ConnectionObject obj = new ConnectionObject();
            obj.ID = id;
            obj.Name = name;
            obj.ConnectionString = connectionString;
            obj.ServerType = servertype;
            obj.CteateDate = createDate;
            return obj;
        }

        public static ConnectionObject CreateConnectionObject(String name, String connectionString, String servertype)
        {
            return FillConnectionObject(Guid.NewGuid(), name, connectionString, servertype, DateTime.UtcNow);
        }

        internal void Save(DbConnection conn)
        {
            if (conn.State == System.Data.ConnectionState.Closed)
            {
                conn.Open();
            }
            DbCommand saveCmd = conn.CreateCommand();
            saveCmd.CommandText = @"IF EXISTS (SELECT Id FROM ConnectionObject WHERE Id = @id)
                   UPDATE ConnectionObject SET [Name]=@name, @ServerType=@serverType WHERE Id = @id
                ELSE
                   INSERT ConnectionObject (Id, [Name], ServerType, CreatedAt) VALUES(@id,@name,@serverType, @createdAt);";

            saveCmd.Parameters["@id"].Value = this.ID;
            saveCmd.Parameters["@name"].Value = this.Name;
            saveCmd.Parameters["@serverType"].Value = this.ServerType;
            saveCmd.Parameters["@createdAt"].Value = this.CteateDate;
            saveCmd.ExecuteNonQuery();
        }
    }
}
